package fm.admin.controller;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.cache.AreaCache;
import fm.controller.BaseController;
import fm.entityEnum.*;
import fm.exception.BizException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.yichenet.mongo.service.ArticleService;
import fm.yichenet.mongo.service.CarouselService;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.mongo.service.ShopMgrService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CM on 17/5/21.
 */
@Controller
@RequestMapping("/portal/config")
public class PortalConfigController extends BaseController {

    @Autowired
    private CarouselService carouselService;
    @Autowired
    private GoodMgrService goodMgrService;
    @Autowired
    private ShopMgrService shopMgrService;
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/index")
    public String index(ModelMap modelMap) {
        modelMap.put("citys", AreaCache.getAllProvince());
        return "/admin/home/portal";
    }
    @RequestMapping("/home")
    public String goHome(ModelMap modelMap) {
        modelMap.put("citys", AreaCache.getAllProvince());
        return "/admin/user_index";
    }
    @ResponseBody
    @RequestMapping("/carousel/list/{scope}")
    public Map carouselList(String city, CarouselType type, @PathVariable CarouselScope scope, String  shopId,Long sectionId) {
        Map res = new HashMap();
        try {
            List<DBObject> list = carouselService.getList(type, scope, city, shopId, null,sectionId);
            res.put("data", list);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/carousel/{scope}/add")
    public Map addCarousel(String uri, String city,Long section,String sectionName, CarouselType type,
                           @PathVariable CarouselScope scope, String typeValue, String startTime,
                           String endTime) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(uri)) {
                throw new BizException("请先上传图片在添加");
            }
            if (StringUtils.isEmpty(city)) {
                throw new BizException("请选择轮播图投放区域");
            }
            if (StringUtils.isEmpty(typeValue)) {
                throw new BizException("请选择/填入对应的" + type.getDesc());
            }
            DBObject object = carouselService.addCarousel(uri, type, scope, typeValue, city, startTime, endTime,section,sectionName);
            res.put("data", object);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/carousel/del")
    public Map delCarousel(String cid) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(cid)) {
                throw new BizException("未找到对应的轮播图，删除失败");
            }
            carouselService.delCarousel(cid);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/mark/good")
    public Map flagGood(GoodFlagEnum goodFlag, String action, String goodId, String city) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(goodId)) {
                throw new RuntimeException("请选择商品!");
            }
            if(StringUtils.isEmpty(city)){
                city="default";
            }
            Map param = new HashMap();
            param.put("good_id", goodId);
            DBObject good = goodMgrService.getGood(param);
            if ("ADD".equals(action)) {
                Map countCondition = new HashMap();
                countCondition.put("flags.name", goodFlag.toString());
                countCondition.put("status", 1+"");
                long count = goodMgrService.countAll(countCondition);

                if (count - goodFlag.getNum() > 0) {
                    throw new BizException(goodFlag.getDesc() + "模块最多只能配置" + goodFlag.getNum() + "个商品!");
                }
                MCondition existsCondition = MCondition.create(MRel.and);
                existsCondition.append("good_id", goodId);
                existsCondition.append("flags.name", goodFlag.toString());
                existsCondition.append("flags.city", city);
                long exists = goodMgrService.countAll(existsCondition.toDBObject().toMap());

                if (exists <= 0) {
                    Map<String, String> flag = new HashMap<>();
                    flag.put("name", goodFlag.toString());
                    flag.put("desc", goodFlag.getDesc());
                    if ("default".equals(city)) {
                        flag.put("city", city);
                        flag.put("city_desc", "默认全国");
                    } else {
                        flag.put("city", city);
                        flag.put("city_desc", AreaCache.getAddress(city).getName());
                    }


                    List<Map<String, String>> flags = null;
                    if (good.containsField("flags")) {
                        flags = (List<Map<String, String>>) good.get("flags");
                    } else {
                        flags = new ArrayList<>();
                    }

                    flags.add(flag);

                    DBObject updateObj = new BasicDBObject("good_id", goodId);
                    updateObj.put("shop_id", good.get("shop_id"));
                    updateObj.put("flags", flags);
                    goodMgrService.updateGood(updateObj.toMap());
                }
            } else if ("DELETE".equals(action)) {
                if (good.containsField("flags")) {
                    List<Map<String, String>> flags = (List<Map<String, String>>) good.get("flags");
                    List<Map<String, String>> newFlags = new ArrayList<>();
                    for (Map<String, String> flag : flags) {
                        String name = flag.get("name");
                        String existsCity = flag.get("city");
                        if (name.equals(goodFlag.toString()) && existsCity.equals(city)) {
                            continue;
                        } else {
                            newFlags.add(flag);
                        }
                    }

                    DBObject updateObject = new BasicDBObject("good_id", goodId);
                    updateObject.put("shop_id", good.get("shop_id"));
                    updateObject.put("flags", newFlags);
                    goodMgrService.updateGood(updateObject.toMap());
                }
            }

            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    /**
     * 店铺显示配置统一入口
     * @param shopId
     * @param action
     * @param city
     * @param pageType
     * @return
     */
    @ResponseBody
    @RequestMapping("/shop/flag")
    public Map portalShopFlag(String shopId, String action, String city,ShopFlagEnum pageType) {
        Map res = new HashMap();
        try {
            if (shopId == null || StringUtils.isEmpty(action)) {
                throw new BizException("参数缺失");
            }
            shopMgrService.flagShop(shopId, action, city,pageType);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/info/{action}")
    public Map infoOperation(String articleId, @PathVariable String action, String area, ArticleAdEnum pageType, String img_id) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(articleId)) {
                throw new BizException("请选择文章");
            }
            if (StringUtils.isEmpty(area)) {
                throw new BizException("请选择要投放的城市");
            }

            DBObject article = articleService.getArticleInfo(articleId);
            if (article == null) {
                throw new BizException("未找到对应的文章信息，配置失败！");
            }
            List<Map<String,String>> flags = (List<Map<String, String>>) article.get("flags");
            MCondition mc = MCondition.create(MRel.and);
            mc.append("flags.name",pageType.toString());
            mc.append("flags.city",area);
//            article.put(pageType+"_area", area);
//            article.put(pageType,1);
//            Map param = new HashMap();
//            param.put("id",articleId);
//            param.put(pageType,1);
            if(img_id==null){
                img_id= (String) article.get("portal_img");
            }
            if ("ADD".equals(action)) {
                int count = (int)  articleService.countArticles(mc.toDBObject().toMap());
                if(count>=pageType.getNum()){
                    throw new BizException("该推广模块只能配置"+pageType.getNum()+"篇资讯");
                }
                boolean existsFlag = false;
                if(flags==null){
                    flags=new ArrayList<>();
                }
                else {
                    for (Map<String, String> flag : flags) {
                        if (flag.get("name").equals(pageType.toString()) && flag.get("city").equals(area)) {
                            existsFlag = true;
                            break;
                        }
                    }
                }
                if(!existsFlag){
                    Map<String,String> newFlag = new HashMap<>();
                    newFlag.put("name",pageType.toString());
                    newFlag.put("city",area);
                    newFlag.put("img",img_id);
                    if("default".equals(area)){
                        newFlag.put("city_desc","默认全国");
                    }
                    else {
                        newFlag.put("city_desc", AreaCache.getAddress(area).getName());
                    }
                    flags.add(newFlag);
                    article.put("flags",flags);
                    articleService.updateArticle(articleId,article);
                }
            }else if ("DELETE".equals(action)) {
                List<Map<String,String>> newflags = new ArrayList<>();
                if(flags.size()>1){
                    for(Map<String,String> flag:flags) {
                        if (flag.get("name").equals(pageType.toString()) && flag.get("city").equals(area)) {

                            continue;
                        } else {
                            newflags.add(flag);
                        }
                    }
                }
                article.put("flags", newflags);
                articleService.updateArticle(articleId,article);
            }

            res.put("data", article);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }
}
